import _ from 'lodash';
import Axios from 'axios';
import Api from './api';

export default class Collection{
    constructor(array, api){
        this.collection = array || [];
        this.api = api || new Api;
    }

    remove(item,sync){
        var index = _.findIndex(this.collection, function(_item) {
            return _item._id == item._id
        });
        if (index === -1) return;
        this.collection.splice(index, 1);

        if(sync) return Axios.post(this.api.removeApi, item);
   }

   add(item,sync){
        var copy  = _.extend({}, item);
        this.collection.push(copy);

        if(sync) return Axios.post(this.api.createApi, item);
   }

   get(id){
       return _.find(array, function(item){
            return _item._id == item._id;
       });
   }

   update(item,sync){
        var index = _.findIndex(this.collection, function(_item) {
            return _item._id == item._id
        });
        if (index === -1) return;
        this.collection.splice(index, 1, item);

        if(sync) return Axios.post(this.api.updateApi, item);
   }
}